﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using Facebook.Web;
using Facebook.Web.FbmlControls;
using System.Text.RegularExpressions;

//Class for form submission
public partial class Form : LutefiskPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Pictures require absolute path to be displayed         
        editImage.ImageUrl = MasterPage.ConvertRelativeUrlToAbsoluteUrl(Page, "~/Images/editmode.png");
    }

    //check the tags for proper input
    protected void checkTags (Object source, ServerValidateEventArgs args)
    {
        string[] temp = delimitTags(args.Value);
        if ((temp[0].Length > 19) || (temp[1].Length > 19) || (temp[2].Length > 19))
            args.IsValid = false;
        else args.IsValid = true;
    }

    //Removes all sql injection issues
    private void cleanseSQL(Control parent)
    {
        //goes through each control on the page
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                cleanseSQL(c);
            }
            else
            {
                //check for text boxes and clean them of injections.
                if ((c.GetType().ToString()) == "System.Web.UI.WebControls.TextBox")
                    ((TextBox)c).Text = Regex.Replace(((TextBox)c).Text, Lutefisk.SQL_CLEANSE_STRING, "", RegexOptions.IgnoreCase);
            }
        }
    }

    //Submission of data fields from the user. 
    protected void submitButtonClick(Object source, EventArgs e)
    {
        // Removes code injections
        cleanseSQL(Page.Page);
        
        bool hasAccount = true;

        //Look if the user is in the database
        using (SqlConnection dbconn = new SqlConnection(Lutefisk.CONNECTION_STRING))
        {
            dbconn.Open();                  //create a connection

            string searchString = "SELECT * FROM musicians WHERE UID=" + CurrentMusician.UID + ";";
            using (SqlCommand sql = new SqlCommand(searchString, dbconn))
            {
                using (SqlDataReader reader = sql.ExecuteReader())
                {
                    if (!reader.HasRows)   //if datareader is empty, the user is not present
                    {
                        hasAccount = false;
                    }
                }
            }
        }

        // If the user is in the database, delete them, then proceed to add them, if not proceed to add them.
        if (hasAccount)
        {
            using (SqlConnection dbconn = new SqlConnection(Lutefisk.CONNECTION_STRING))
            {
                dbconn.Open();

                string sqlDelete = "DELETE * FROM musicians WHERE UID=" + CurrentMusician.UID + ";";

                //execute the command
                using (SqlCommand cmd = new SqlCommand(sqlDelete, dbconn))
                {
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException ax)
                    {
                        formSubmitLabel.Text = "Error occured!";
                    }
                }
            }

        }
        

        // Split up the tags
        string[] tags = delimitTags(tagsBox.Text);
        
        // Define the information to insert into the database. This is ugly. It's just SQL.
        string sqlInsert = "INSERT INTO musicians " +
           "VALUES ('" + CurrentMusician.UID + "','" + nameBox.Text + "','" + labelBox.Text + "', '" + pictureBox.Text + "', '" + bioBox.Text + "', '" + websiteBox.Text + "', '" + experienceBox.Text + "',"
            + "'" + influencesBox.Text + "', '" + tags[0] + "', '" + tags[1] + "', '" + tags[2] + "', '" + "" + "', '" + "" + "', '" + "" + "', '"+0+ "');";

        //create an SQL connection.
        using (SqlConnection dbconn = new SqlConnection(Lutefisk.CONNECTION_STRING))
        {
            dbconn.Open();

            //execute the command
            using (SqlCommand cmd = new SqlCommand(sqlInsert, dbconn))
            {
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ax)
                {
                    formSubmitLabel.Text = "Please check your data and recorrect your error!";
                }
            }
        }        
        
        // Direct User back to Default (profile) page once all forms are filled in.
        if (Page.IsValid)
        {
            Lutefisk.DirectPage(Page.Page, "Default");                              //redirect user to fresh profile!        
        }
        else { clearControls(Page.Page); }
    }
    
    //clear all controls to re-enter new information. This must be done recursively. Yuck.
    private void clearControls(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                clearControls(c);
            }
            else
            {
                //check for all control types. This is slick.
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;
                }
            }
        }
    }

    /// <summary>
    /// Split all the tags by using commas 
    /// </summary>
    /// <param name="tagsCommas">Tag string from textbox.</param>
    /// <returns></returns>
    private string[] delimitTags(string tagsCommas)
    {
        string[] tags = new string[3] { "", "", "" };                   //define three tags
        char[] delimiter = { ',' };                                     //define the delimiter
        string[] tempTags = tagsCommas.Split(delimiter);                //delimit the input

        //transfer the tags
        for (int i = 0; (i < tempTags.Length) && (i < 3); i++)
        {
            tags[i] = tempTags[i];
        }

        //return the tags
        return tags;
    }

    protected void editProfileClick(object sender, EventArgs e)
    {
        Lutefisk.DirectPage(Page.Page, "Form");
    }
    protected void editMultimediaClick(object sender, EventArgs e)
    {
        Lutefisk.DirectPage(Page.Page, "UploadMultimedia");
    }
    protected void editCurriculumVitaeClick(object sender, EventArgs e)
    {
        Lutefisk.DirectPage(Page.Page, "UploadCV");
    }
}